package com.cychat.mall.controller;

import cn.hutool.core.bean.BeanUtil;
import com.Cychat.commons.entity.ResultMessage;
import com.Cychat.commons.entity.pojo.Address;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cychat.mall.entity.DTO.AddressDTO;
import com.cychat.mall.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-11-5:上午 10:42  <br/>
 * Description: 地址控制器
 */
@RestController
@RequestMapping("/api/mall")
@CrossOrigin
public class AddressController {
    @Autowired
    private AddressService addressService;
    // 获取用户地址列表
    @GetMapping("/address/list/{userId}")
    public ResultMessage list(
            @PathVariable("userId") Long userId
    ) {
        try {
            // 调用服务层方法获取用户地址列表
            List<Address> addressList = addressService.listByUserId(userId);
            // 转换为 DTO 列表
            List<AddressDTO> dtoList = addressList.stream()
                    .map(address -> {
                        AddressDTO dto = new AddressDTO();
                        dto.setAddressId(address.getAddressId());
                        dto.setUserId(String.valueOf(address.getUserId())); //  Long → String
                        dto.setReceiverName(address.getReceiverName());
                        dto.setReceiverPhone(address.getReceiverPhone());
                        dto.setProvince(address.getProvince());
                        dto.setCity(address.getCity());
                        dto.setDistrict(address.getDistrict());
                        dto.setDetailAddress(address.getDetailAddress());
                        dto.setIsDefault(address.getIsDefault());
                        dto.setCreateTime(address.getCreateTime());
                        dto.setUpdateTime(address.getUpdateTime());
                        return dto;
                    })
                    .collect(Collectors.toList());
            // 返回结果
            return ResultMessage.success(dtoList);
        } catch (Exception e) {
            return ResultMessage.error("获取地址列表失败: " + e.getMessage());
        }
    }

    // 新增地址
    @PostMapping("/address/add/{userId}")
    public ResultMessage<Void> add(
            @PathVariable("userId") Long userId,
            @RequestBody Address address
    ) {
        try {
            // 设置用户ID
            address.setUserId(userId);
            // 设置创建时间和更新时间
            if(address.getIsDefault() == 1){
                //设置默认地址时，其他地址的isDefault字段设置为0
                LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Address::getUserId, userId);
                queryWrapper.ne(Address::getAddressId, address.getAddressId());
                Address updateAddress = new Address();
                updateAddress.setUserId(userId); // 如果需要设置 userId
                updateAddress.setIsDefault(0);
                addressService.update(updateAddress, queryWrapper);
            }
            address.setCreateTime(new Date());
            address.setUpdateTime(new Date());
            // 调用服务层方法新增地址
            addressService.saveOrUpdate(address);
            // 返回结果
            return ResultMessage.success();
        } catch (Exception e) {
            return ResultMessage.error("新增地址失败: " + e.getMessage());
        }
    }

    // 删除地址
    @DeleteMapping("/address/delete/{userId}")
    public ResultMessage<Void> delete(
            @PathVariable("userId") Long userId,
            @RequestParam("addressId") Integer addressId
    ) {
        try {
            // 调用服务层方法删除地址
            addressService.removeById(addressId);
            // 返回结果
            return ResultMessage.success();
        } catch (Exception e) {
            return ResultMessage.error("删除地址失败: " + e.getMessage());
        }
    }

    // 设置默认地址
    @PutMapping("/address/setDefault/{userId}")
    public ResultMessage<Void> setDefault(
            @PathVariable("userId") Long userId,
            @RequestParam("addressId") Integer addressId
    ) {

        try {
            // 检查地址是否存在
            Address address = addressService.getById(addressId);
            if (address == null) {
                return ResultMessage.error("地址不存在");
            }

            // 检查地址是否属于用户
            if (!address.getUserId().equals(userId)) {
                return ResultMessage.error("地址不属于用户");
            }

            //默认地址只有一个，设置默认地址时，查询其他地址的isDefault字段，如果为1，则设置为0
            List<Address> addressList = addressService.listByUserId(userId);
            for (Address addr : addressList) {
                if (!addr.getAddressId().equals(addressId) && addr.getIsDefault() == 1) {
                    addr.setIsDefault(0);
                    addressService.updateById(addr);
                }
            }

            // 调用服务层方法设置默认地址
            addressService.setDefault(addressId);
            // 返回结果
            return ResultMessage.success();
        } catch (Exception e) {
            return ResultMessage.error("设置默认地址失败: " + e.getMessage());
        }
    }

    // 获取默认地址
    @GetMapping("/address/getDefault/{userId}")
    public ResultMessage<Address> getDefault(
            @PathVariable("userId") Long userId
    ) {
        try {
            // 调用服务层方法获取默认地址
            Address defaultAddress = addressService.getDefaultByUserId(userId);
            // 返回结果
            return ResultMessage.success(defaultAddress);
        } catch (Exception e) {
            return ResultMessage.error("获取默认地址失败: " + e.getMessage());
        }
    }

    // 更新地址
    @PutMapping("/address/update/{userId}")
    public ResultMessage<Void> update(
            @PathVariable("userId") Long userId,
            @RequestBody AddressDTO address
    ) {
        try {
            // 检查地址是否存在
            Address existingAddress = addressService.getById(address.getAddressId());
            if (existingAddress == null) {
                return ResultMessage.error("地址不存在");
            }

            // 检查地址是否属于用户
            if (!existingAddress.getUserId().equals(userId)) {
                return ResultMessage.error("地址不属于用户");
            }

            // 设置更新时间
            address.setUpdateTime(new Date());

            //查询更新地址是否为默认地址
            if (address.getIsDefault() == 1) {
                //如果更新地址为默认地址，则其他地址的isDefault字段设置为0
                addressService.setDefault(address.getAddressId());
                List<Address> addressList = addressService.listByUserId(userId);
                for (Address addr : addressList) {
                    if (!addr.getAddressId().equals(address.getAddressId()) && addr.getIsDefault() == 1) {
                        addr.setIsDefault(0);
                        addressService.updateById(addr);
                    }
                }
            }

            // 调用服务层方法更新地址
            System.out.println("address:"+address);
            // 转换为实体类
            Address updateAddress = BeanUtil.copyProperties(address, Address.class);
            System.out.println("updateAddress:"+updateAddress);
            addressService.updateById(updateAddress);
            // 返回结果
            return ResultMessage.success();
        } catch (Exception e) {
            return ResultMessage.error("更新地址失败: " + e.getMessage());
        }
    }


}
